package com.example.play.vm

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.common.entity.CommendEntity
import com.example.common.entity.CommendReply
import com.example.common.entity.DanmuEntity
import com.example.common.vm.BaseViewModel
import com.example.play.intent.PlayViewIntent
import com.example.play.repo.PlayVideoRepository
import com.example.play.state.PlayUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

@HiltViewModel
class PlayViewModel: BaseViewModel<PlayViewIntent>() {
    private val repository: PlayVideoRepository = PlayVideoRepository()
    private val _uiStateFlow = MutableSharedFlow<PlayUiState>()
    val uiStateFlow : SharedFlow<PlayUiState> = _uiStateFlow.asSharedFlow()
    override fun dispatchIntent(intent: PlayViewIntent) {
        when(intent){
            is PlayViewIntent.LoadAuthorById->loadAuthorById(intent.userid)
            is PlayViewIntent.LoadRecommendSimpleVideo -> loadRecommendSimpleVideo(intent.page, intent.pageSize)
            is PlayViewIntent.LoadSimpleVideoByChannelId -> loadSimpleVideoByChannelId(intent.channelId, intent.page, intent.pageSize)
            is PlayViewIntent.LoadRecommendMutilVideo -> loadRecommendMutilVideo(intent.page, intent.pageSize)
            is PlayViewIntent.LoadMutilVideoByTypeId -> loadMutilVideoByTypeId(intent.typeid,intent.page,intent.pageSize)
            is PlayViewIntent.LoadVideoCommends -> loadVideoCommends(intent.dataType,intent.itemId)
            is PlayViewIntent.PublishComment -> publishComment(intent.entity)
            is PlayViewIntent.PublishDanmuMsg -> publishDanmuMsg(intent.entity)
            is PlayViewIntent.LoadVideoDanmuMsg -> loadVideoDanmuMsg(intent.datatype,intent.itemid)
        }
    }

    //模拟评论回复数据
    private var mockReplayComment = listOf(
        CommendReply(0, 0, "我来了", "2023-12-20 14:23:21", 0, "芝士雪豹", 0, 1, "https://ww2.sinaimg.cn/mw690/005Zk4Aqgy1hqcerik29rj30u012w76n.jpg" ),
        CommendReply(0, 0, "假的真不了", "2023-12-20 14:23:23", 1, "虾仁不眨眼", 0, 1, "https://wx4.sinaimg.cn/mw690/006faMndly1hqns4dao43j30u0140401.jpg" ),
        CommendReply(0, 0, "言之有理", "2023-12-20 14:23:25", 2, "熊猫很困", 0, 1, "https://wx1.sinaimg.cn/mw690/005OayIHly1hqdnyvre3zj30w70w7do8.jpg" ),
        CommendReply(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 3, "鱼香 rose", 0, 1, "https://q9.itc.cn/q_70/images03/20240829/e9b4ccc3579f4787976d3458229fe1a1.jpeg" ),
        CommendReply(0, 0, "啥也不是！！", "2023-12-20 14:23:26", 4, "吃土少女", 0, 1, "https://img1.baidu.com/it/u=3254750559,1502332285&fm=253&fmt=auto&app=120&f=GIF?w=285&h=285" ),
        CommendReply(0, 0, "太傻了！！", "2023-12-20 14:23:26", 5, "摆烂小柯基", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 6, "摸鱼喵星人", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "给你点赞！！", "2023-12-20 14:23:26", 7, "睡不醒的猪", 0, 1, "https://p1-dy.bytexservice.com/img/user-avatar/d71e237251a88a91222c30a4dc3bf9e6~300x300.image" ),
        CommendReply(0, 0, "努力加油！！", "2023-12-20 14:23:26", 8, "暴躁小松鼠", 0, 1, "https://img1.baidu.com/it/u=3053515689,4170843785&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" ),
        CommendReply(0, 0, "我觉得太假了，一点儿不真实！！", "2023-12-20 14:23:26", 9, "干饭小仓鼠", 0, 1, "https://img1.baidu.com/it/u=3053515689,4170843785&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500" ),
        CommendReply(0, 0, "加油！！", "2023-12-20 14:23:26", 10, "减肥版干饭王", 0, 1, "https://q9.itc.cn/q_70/images03/20240829/e9b4ccc3579f4787976d3458229fe1a1.jpeg" ),
        CommendReply(0, 0, "一点儿不真实！！", "2023-12-20 14:23:26", 11, "外卖依赖症", 0, 1, "" ),
        CommendReply(0, 0, "牛逼牛逼，太漂亮了！！", "2023-12-20 14:23:26", 12, "气泡音小笨蛋", 0, 1, "https://img0.baidu.com/it/u=306649616,2230355986&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500" ),
    )

    //获取视频作者信息
    private fun loadAuthorById(userid: String) {
        mViewModelScope.launch (mDispatcher){
            //发送请求并收集数据
            repository.getAuthorById(userid).collect{list->
                if (list!=null){
                    _uiStateFlow.emit(PlayUiState.LoadAuthorByIdSuccess(list))
                }else{
                    _uiStateFlow.emit(PlayUiState.LoadAuthorByIdFail("没有获取到数据!"))
                }
            }
        }
    }

    //获取首页推荐视频
    private fun loadRecommendSimpleVideo(page: Int, pageSize: Int) {
        mViewModelScope.launch (mDispatcher){
            //发送请求并收集数据
            repository.getRecommendSimpleVideo(page,pageSize).collect{list->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(PlayUiState.LoadRecommendSimpleVideoSuccess(list))
                }else{
                    _uiStateFlow.emit(PlayUiState.LoadRecommendSimpleVideoFail("没有获取到数据!"))
                }
            }
        }
    }

    //获取首页分类下的视频
    private fun loadSimpleVideoByChannelId(channelId: String, page: Int, pageSize: Int) {
        mViewModelScope.launch (mDispatcher){
            //发送请求并收集数据
            repository.getSimpleVideoByChannelId(channelId,page,pageSize).collect{list->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(PlayUiState.LoadSimpleVideoByChannelIdSuccess(list))
                }else{
                    _uiStateFlow.emit(PlayUiState.LoadSimpleVideoByChannelIdFail("没有获取到数据!"))
                }
            }
        }
    }

    //获取放映厅推荐视频
    private fun loadRecommendMutilVideo(page: Int, pageSize: Int) {
        mViewModelScope.launch (mDispatcher){
            //发送请求并收集数据
            repository.getRecommendMutilVideo(page, pageSize).collect{list->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(PlayUiState.LoadRecommendMutilVideoSuccess(list))
                }else{
                    _uiStateFlow.emit(PlayUiState.LoadRecommendMutilVideoFail("没有获取到数据!"))
                }
            }
        }
    }

    //获取放映厅分类下视频
    private fun loadMutilVideoByTypeId(typeid: Int, page: Int, pageSize: Int) {
        mViewModelScope.launch (mDispatcher){
            //发送请求并收集数据
            repository.getMutilVideoByTypeId(typeid, page, pageSize).collect{list->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(PlayUiState.LoadMutilVideoByTypeIdSuccess(list))
                }else{
                    _uiStateFlow.emit(PlayUiState.LoadMutilVideoByTypeIdFail("没有获取到数据!"))
                }
            }
        }
    }

    //获取视频评论
    private fun loadVideoCommends(dataType: Int, itemId: String) {
        mViewModelScope.launch (mDispatcher){
            //发送请求并收集数据
            repository.getVideoCommends(dataType, itemId).collect{list->
                if (list.isNotEmpty()){
                    list.forEach {
                        randomConfigReplayComment(it)
                    }
                    _uiStateFlow.emit(PlayUiState.LoadVideoCommendsSuccess(list))
                }else{
                    _uiStateFlow.emit(PlayUiState.LoadVideoCommendsFail("没有获取到数据!"))
                }
            }
        }
    }

    //发布评论
    private fun publishComment(entity: CommendEntity) {
        mViewModelScope.launch(mDispatcher) {
            //封装Body参数
            val requestBody: RequestBody = GsonUtils.toJson(entity).toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
            repository.publishComment(requestBody).collect{ list ->
                ToastUtils.showLong("发送评论成功")
                loadVideoCommends(list.datatype, list.itemid.toString())
            }
        }
    }

    //发布弹幕
    private fun publishDanmuMsg(entity: DanmuEntity) {
        mViewModelScope.launch(mDispatcher) {
            //封装Body参数
            val requestBody: RequestBody = GsonUtils.toJson(entity).toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
            repository.publishDanmuMsg(requestBody).collect{ list ->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(PlayUiState.PublishDanmuMsgSuccess(list))
                } else {
                    _uiStateFlow.emit(PlayUiState.PublishDanmuMsgFail("没有获取到数据!"))
                }
            }
        }
    }

    //获取弹幕
    private fun loadVideoDanmuMsg(datatype: Int ,itemid: String) {
        mViewModelScope.launch (mDispatcher){
            //发送请求并收集数据
            repository.getVideoDanmuMsg(datatype, itemid).collect{list->
                if (list.isNotEmpty()){
                    _uiStateFlow.emit(PlayUiState.LoadVideoDanmuMsgSuccess(list))
                }else{
                    _uiStateFlow.emit(PlayUiState.LoadVideoDanmuMsgFail("没有获取到数据!"))
                }
            }
        }
    }

    /**
     * 随机模拟评论回复
     */
    private fun randomConfigReplayComment(entity: CommendEntity){
        //设置头像
        entity.userlogo = "https://q3.itc.cn/q_70/images03/20250110/1e71eecf56b34344bcae6a5b85c0bec2.jpeg"
        var randomNum = (Math.random() * 10 + 1).toInt()
        entity.replytotal = randomNum
        //二级评论
        while (randomNum > 0){
            val fromIndex = (mockReplayComment.size - 2) % ((Math.random() * 10).toInt() + 1)
            entity.replyList.addAll(mockReplayComment.subList(fromIndex, fromIndex + 1))
            randomNum -=1
        }
    }
}